<template>
  <el-card shadow="never">
    <el-row>
      <el-button type="primary" @click="toAdd">新增</el-button>
    </el-row>
    <el-row>
      <el-table :data="tableList" :border="true" :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        :default-sort="{ prop: listConfig.defaultOrderBy, order: listConfig.defaultOrder, init: false }"
        @sort-change="handleSortChange">
        <el-table-column v-for="(item, index) in tableConfig" :prop="item.fieldName" :label="item.fieldText"
          :sortable="item.isSort ? 'custom' : false" :label-class-name="setSortClass(item.fieldName)">
          <template #header v-if="item.isSearch">
            <ColumnSearch v-model="tableConfig[index]" :query="queryValue(item.fieldName)" @query="query()" />
          </template>
          <template #default="scope">
            <ColumnRender v-model="tableConfig[index]" :fieldValue="scope.row[item.fieldName]"
              :formItemList="formItemList" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" link :icon="EditPen" @click="toEdit(scope.row.Id)">
              编辑
            </el-button>
            <el-button type="danger" link :icon="Delete" @click="toDelete(scope.row.Id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <div class="table-buttom-options">
        <Pagination :total="search.total" v-model:pageIndex="search.pageIndex" v-model:pageSize="search.pageSize"
          @change="query()" />
      </div>
    </el-row>
    <!-- 表单弹框 -->
    <FormRender v-if="open" v-model="open" :formSetting="formSetting" @submit="submit" :data="instanceFormData"
      :operateType="formOperateType" />
  </el-card>
</template>

<script setup lang="ts">
import { Plus, Delete, EditPen, Search, Promotion } from "@element-plus/icons-vue";
import DesignInstanceApi, { DesignInstanceEdit, DesignInstanceQuery } from '@/api/design/designInstance';
import { FormField, FormOperateType, FormSetting } from '@/components/DesignForm';
import successMsg from '@/utils/successMsg';
import { DesignListConfig, DesignListTableConfig } from "@/components/DesignList";

const route = useRoute(); //实例化路由
const listId = route.params.ListId as string;

const listConfig = ref<DesignListConfig>({});
const tableConfig = ref<DesignListTableConfig[]>([]);

const formSetting = ref<FormSetting>({
  formConfig: {},
  formStyle: {
    inline: false,
    labelPosition: 'left',
    labelWidth: 'auto',
    labelSuffix: '',
    hideRequiredAsterisk: false,
    requireAsteriskPosition: 'right',
    showMessage: true,
    inlineMessage: false,
    statusIcon: false,
    disabled: false,
    validateOnRuleChange: true,
    scrollToError: false
  },
  formItemList: [],
});

// 表格实例
const search = reactive<DesignInstanceQuery>({
  searchString: "",
  query: [],
  sorts: [],
  total: 0,
  pageIndex: 1, //第几页
  pageSize: 10, //每页多少条
  listId: listId
})

// 点击排序
const handleSortChange = async (data: { column: any, prop: string, order: any }) => {
  search.sorts = search.sorts.filter(x => x.field != data.prop);
  search.sorts.push({ field: data.prop, order: data.order });
  await query();
}

const setSortClass = (field: string) => {
  const sort = search.sorts.find(x => x.field === field);
  return sort ? sort.order : "";
}

const formItemList = ref<FormField[]>([]);
onMounted(async () => {
  const config = await DesignInstanceApi.queryConfig(listId);

  listConfig.value = config.listConfig;
  tableConfig.value = JSON.parse(config.tableConfig);

  Object.assign(formSetting.value, config.formSetting)
  formSetting.value.formConfig = JSON.parse(config.formSetting.formConfig);
  formSetting.value.formItemList = JSON.parse(config.formSetting.formItemList);
  formSetting.value.formStyle = JSON.parse(config.formSetting.formStyle);
  formItemList.value = getFieldItemList(formSetting.value.formItemList);

  // 查询条件
  search.query = tableConfig.value.filter(x => x.isSearch).map(x => {
    return {
      fieldName: x.fieldName,
      fieldValue: x.fieldType === 'radio' || x.fieldType === 'checkbox' ? [] : null
    };
  });

  await query();
})

const queryValue = (fieldName: string) => {
  const field = search.query.find(x => x.fieldName === fieldName);
  return field || {};
}

const getFieldItemList = (list: FormField[]): FormField[] => {
  const formItemList = [];
  list.forEach(x => {
    getFiledOption(formItemList, x);
  })
  return formItemList;
}

const getFiledOption = (formItemList, formItem: FormField) => {
  if (formItem.group === 'form') {
    formItemList.push(formItem);
  } else if (formItem.group === 'layout') {
    formItem.formItemList.forEach(x => {
      getFiledOption(formItemList, x);
    })
  }
}

const tableList = ref<object[]>([]);
const query = async () => {
  const { dataList, totalCount } = await DesignInstanceApi.query(search);
  tableList.value = dataList;
  search.total = totalCount;
}

const instanceFormData = ref<object>({});
const formOperateType = ref<FormOperateType>();
const open = ref(false);
const toAdd = () => {
  instanceFormData.value = {};
  open.value = true;
  formOperateType.value = 'create';
}

const toEdit = async (id: string) => {
  const data = await DesignInstanceApi.details(formSetting.value.id, id);
  instanceFormData.value = data;
  open.value = true;
  formOperateType.value = 'update';
}

const toDelete = async (id: string) => {
  const { success, message } = await DesignInstanceApi.delete(formSetting.value.id, id);
  successMsg(success, message, await query());
}

const form = ref<DesignInstanceEdit>({});
const submit = async (data: any) => {
  form.value.formId = formSetting.value.id;
  form.value.formData = JSON.stringify(data);
  const { success, message } = await DesignInstanceApi[formOperateType.value](form.value);
  successMsg(success, message, async () => {
    open.value = false;
    await query();
  })
}
</script>

<style lang="scss" scoped></style>
